package com.lei.study.depth.zookeeper;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * <p>
 * 原生zk客户端 测试
 * </p>
 *
 * @author <a href='mailto:17674030991@163.com'/>伍磊
 */
public class ZookeeperClientTest {

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zkClient = new ZooKeeper("127.0.0.1:2181", 5000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("连接: " + event);
            }
        });

        /**
         * 数据修改 watch -> 只触发一次
         */
        Stat stat = new Stat();
        String data = new String(zkClient.getData("/lei", new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("watch 节点触发的事件: " + event);

                // 数据改变事件
                if (Event.EventType.NodeDataChanged.equals(event.getType())) {
                    System.out.println("数据发生变更");
                }
            }
        }, stat));
        System.out.println("数据: " + data);

        /**
         * 回调
         * watch 为true表示使用默认的 监听器
         */
        zkClient.getData("/lei", true, new AsyncCallback.DataCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
                System.out.println("回调结果: " + new String(data));
            }
        }, null);

        System.in.read();
    }
}
